package com.atguigu.java8.stream;

import org.junit.Test;

import java.time.Duration;
import java.time.Instant;
import java.util.concurrent.ForkJoinPool;
import java.util.stream.LongStream;

public class ForkJoinTest {

    // Fork-Join框架
    @Test
    public void test1() {
        Instant start = Instant.now();

        ForkJoinPool forkJoinPool = new ForkJoinPool();
        ForkJoinCaculate forkJoinCaculate = new ForkJoinCaculate(0, 10_0000_0000);
        Long value = forkJoinPool.invoke(forkJoinCaculate);
        System.out.println(value);

        Instant end = Instant.now();
        long millis = Duration.between(start, end).toMillis();
        System.out.println("cost:" + millis + "ms");
    }

    // 普通for
    @Test
    public void test2() {
        Instant start = Instant.now();

        long sum = 0;
        for (int i = 0; i < 10_0000_0000; i++) {
            sum += i;
        }
        System.out.println(sum);

        Instant end = Instant.now();
        long millis = Duration.between(start, end).toMillis();
        System.out.println("cost:" + millis + "ms");
    }

    // Java8并行流
    @Test
    public void test3() {
        Instant start = Instant.now();

        long sum = LongStream.rangeClosed(0, 10_0000_0000)
                // 串行流
                // .sequential()
                // 并行流
                .parallel()
                .sum();
        System.out.println(sum);

        Instant end = Instant.now();
        long millis = Duration.between(start, end).toMillis();
        System.out.println("cost:" + millis + "ms");
    }

}
